import axios from 'axios'

export default (data) => {
  const isGet = /get/gi.test(data.method)
  let { url, query } = data

  // 拼接get query string
  if (isGet && query && typeof query === 'object') {
    let queryStr = ''
    for (let key in query) { queryStr += `&${key}=${query[key]}` }
    url += queryStr.replace(/^&/, '?')
  }
  if (isGet && query && typeof query === 'string') {
    url += query
  }

  // 设置选项
  let config = {
    method: isGet ? 'GET' : 'POST',
    timeout: 5000,
    url: isGet ? `/dispatch?path=${url}` : '/dispatch',
    data: isGet ? null : data,
  }

  // 创建axios实例
  const service = axios.create(config)

  // respone拦截器
  service.interceptors.response.use(
    response => {
      const res = response.data
      if (!res.msg || res.success) {
        return response.data
      } else {
        return console.log(res.msg) // for user
      }
    },
    error => {
      console.log('err' + error)// for debug
      console.log(error.message)// for user
      return Promise.reject(error)
    }
  )

  return service()
}
